package com.ssm.blog.service.impl;

import com.ssm.blog.dao.MenuDAO;
import com.ssm.blog.dao.PermissionDAO;
import com.ssm.blog.pojo.AdminUser;
import com.ssm.blog.pojo.Menu;
import com.ssm.blog.pojo.TreeNode;
import com.ssm.blog.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private PermissionDAO permissionDAO;
    @Autowired
    private MenuDAO menuDAO;

    @Override
    public List<TreeNode> getUserMenu(AdminUser user) {
        //查询出用户所有的权限菜单
        List<TreeNode> menus = permissionDAO.getUserMenuByUserId(user.getId());
        return makeTree(menus);
    }

    private List<TreeNode> makeTree(List<TreeNode> menus) {
        Map<Integer, TreeNode> map = new HashMap<>();
        for (TreeNode menu : menus) {
            map.put(menu.getId(), menu);
        }
        for (TreeNode menu : menus) {
            //组装子菜单
            //menu.getParentId() != null代表当前的菜单是子菜单
            TreeNode parent = map.get(menu.getAttributes().getParentId());
            if (parent != null) {
                map.get(menu.getAttributes().getParentId()).getChildren().add(menu);
            }
        }
        //1是根节点，返回根节点的子菜单就是一级菜单
        return map.get(1).getChildren();
    }

    @Override
    public List<TreeNode> getAllMenu() {
        List<TreeNode> allMenu = new ArrayList<>();
        //编辑菜单的时候，如果添加一级菜单，需要将父菜单选成根节点
        TreeNode root = new TreeNode();
        root.setId(1);
        root.setText("根节点");
        allMenu.add(root);
        List<TreeNode> menus = menuDAO.getAllMenu();
        allMenu.addAll(makeTree(menus));
        return allMenu;
    }

    @Override
    public void addMenu(Menu menu) {
        menuDAO.addMenu(menu);
    }

    @Override
    public void updateMenu(Menu menu) {
        menuDAO.updateMenu(menu);
    }

    @Override
    public void deleteMenu(Integer[] ids) {
        for (Integer id : ids) {
            if (id == 1) {// 根菜单不能删除
                return;
            }
            menuDAO.deleteMenu(id);
            menuDAO.updateParentId(id);// 当前菜单的子菜单全部转到根菜单下
            permissionDAO.deleteRolePermissionByMenuId(id);// 删除角色的此项权限
        }
    }

}
